package org.liu;

/**
 * Created by emliu on 2015/5/15.
 */
public class Ground {
    public static final int WIDTH = 20;
    public static final int HEIGHT = 30;
    public int[][] data = new int[HEIGHT][WIDTH];

    public void clear() {
        for(int x = 0; x < WIDTH; ++x) {
            for(int y = 0; y < HEIGHT; ++y) {
                data[y][x] = Main.BLOCK_NONE;
            }
        }
    }

    public boolean collision(Entity e) {
        for(int x = 0; x < e.width; ++x) {
            for(int y = 0; y < e.height; ++y) {
                if(e.data[y][x] != 0) {
                    int X = e.x + x;
                    int Y = e.y + y;
                    if (Y >= 0 && Y < Ground.HEIGHT && X >= 0 && X < Ground.WIDTH) {
                        if (data[e.y + y][e.x + x] != Main.BLOCK_NONE)
                            return true; // collision with blocks exists
                    } else return true; // collision with ground bounds
                }
            }
        }
        return false;
    }

    public int collapse() {
        int src, dest, count = 0;
        for(src = dest = Ground.HEIGHT - 1; dest >= 0; --dest, --src) {
            if(src >= 0) {
                boolean complete = true;
                do {
                    for (int i = 0; i < Ground.WIDTH; ++i) if (data[src][i] == Main.BLOCK_NONE) complete = false;
                    if(complete) --src;
                    else break;
                    ++count;
                }while(src >= 0);
            }

            if(src >= 0) {
                System.arraycopy(data[src], 0, data[dest], 0, Ground.WIDTH);
            } else {
                for(int i = 0; i < Ground.WIDTH; ++i) data[dest][i] = Main.BLOCK_NONE;
            }
        }
        return count;
    }

    public void place(Entity e) {
        for(int x = 0; x < e.width; ++x) {
            for(int y = 0; y < e.height; ++y) {
                if(e.data[y][x] != 0)
                    data[e.y + y][e.x + x] = e.color;
            }
        }
    }
}
